<?php
class Poll_Model_Poll extends Core_Model_Item_Abstract {
    public function getParent($type = 'user') {return Engine_Api::_()->user()->getUser($this->user_id);}
    public function getTitle() {return $this->title;}
    public function getOwner() {return $this->getParent();}
    public function getHref() {
        return Zend_Controller_Front::getInstance()->getRouter()
            ->assemble(array( 
          'controller' => 'poll',
          'action' => 'show-all-options',
          'poll' => $this->getIdentity()), 'poll_general', true);
        //return "javascript:Poll.show({$this->getIdentity()}, '{$this->getTitle()}')";
    }
    public function likes() {
        return new Engine_ProxyObject($this, Engine_Api::_()->getDbtable('likes', 'core'));
    }
    public function comments() {
        return new Engine_ProxyObject($this, Engine_Api::_()->getDbtable('comments', 'core'));
    }
    
    public function isFollowed($user, $obj = false) {
        $tb = Engine_Api::_()->getDbTable('Follow', 'Poll');    
        $sl = $tb->select()->where('user_id = ?', $user->getIdentity())->where('question_id = ?', $this->getIdentity());
        $r  = $tb->fetchRow($sl);
        if ($obj) return $r;
        if ($r) return true;
        return false;
    }
    
    public function getFollowers() {
        $uTb = Engine_Api::_()->getDbTable('Users', 'User');
        $tb = Engine_Api::_()->getDbTable('Follow', 'Poll');    
        $sl = $uTb->select()
            ->setIntegrityCheck(false)
            ->from(array('u' => $uTb->info('name')))
            ->join(array('f' => $tb->info('name')), 'u.user_id = f.user_id', NULL)
            ->where('f.question_id = ?', $this->getIdentity());
        return $uTb->fetchAll($sl);
    }
	
	public function getPhotoUrl($type = 'thumb.profile'){
		//$return $this->getOwner()->getPhotoUrl($type);
		$user = Engine_Api::_()->getItem('user', $this->user_id);
		if($user){
			return $user->getPhotoUrl($type);
		}
	}
    
    public function broadcast($type = NULL, $params = array()) {
        if (!isset($type)) return false;
        $users = $this->getFollowers();
        if (isset($users) && count($users)) {
            $mailer  = Engine_Api::_()->getApi('Mail', 'Core');
            $notifTb = Engine_Api::_()->getDbTable('Notifications', 'Activity');
            $db      = $notifTb->getAdapter();
            $db->beginTransaction();
            try {
                $viewer = $params['viewer'];
                $owner = $this->getOwner(); 
                $recipients = array();  
                if ($viewer->getIdentity() != $owner->getIdentity()){
                    $notifTb->addNotification($owner, $viewer, $this, "poll_$type", array('answer' => $params['answer']));                                
                    $recipients[] = $owner;
                } 
                foreach ($users as $user) {
                    if ($user->getIdentity() == $viewer->getIdentity()) continue;
                    $notifTb->addNotification($user, $viewer, $this, "poll_$type", array('answer' => $params['answer']));                            
                    $recipients[] = $user;
                }                   
                $db->commit();
                
                $mailer->sendSystemRaw($recipients, 'poll_vote', array(
                    'sender_title' => $viewer->getTitle(),
                    'object_title' => $this->getTitle(),
                    'object_link'  => 'http://' . $_SERVER['SERVER_NAME'] . $this->getHref()
                ));
            } catch (Exception $e) {$db->rollBack();}            
        }
    }
    
    public function getOptions($params = array()) {
        $table = Engine_Api::_()->getDbTable('Options', 'Poll');
        $sl    = $table->select()->where('poll_id = ?', $this->getIdentity());
        
        if ( isset($params['get-all']) && $params['get-all'] == true ) return $table->fetchAll($sl);
        return Zend_Paginator::factory($sl);
    }
    
    public function getRichContent() {
        $view = new Zend_View();
        return $view->partial('_displayPoll.tpl', 'poll', array('item' => $this, 'options' => $this->getOptions(), 'isFeed' => true));
    }
    
    public function getUserVoted($user = NULL) {
        if (!$user) $user = Engine_Api::_()->user()->getViewer();
        $tb = $this->getTable();
        $sl = $tb->select();
        $sl->setIntegrityCheck(false)
            ->from(array('eq' => $tb->info('name')), NULL)
            ->joinLeft(array('eo' => 'engine4_poll_options'), 'eq.poll_id = eo.poll_id', NULL)
            ->joinLeft(array('ev' => 'engine4_poll_votes'), 'eo.poll_option_id = ev.option_id', 'option_id')
            ->where('ev.user_id = ?', $user->getIdentity());
        $rs = $tb->fetchAll($sl);
        $voted = array();
        foreach ($rs as $item) {
            $voted[] = $item->option_id;
        }
        return $voted;
    }
}
